<template>
  <div id="app" style="font-size: 26px; font-weght: bold; margin: 30px 0">
    <header class="header">
      <!-- <el-input
        placeholder=""
        v-for="(item, index) in topInputList"
        :key="index"
        v-model="item.text"
        :placeholder="item.title"
        class="top-input"
      ></el-input> -->
      <!-- <el-button type="primary" icon="el-icon-search" @click="search" -->
      <!-- >搜索</el-button -->

      <el-button type="primary" icon="el-icon-plus" @click="handleEdit"
        >添加</el-button
      >
    </header>

    <el-table v-loading="loading" :data="tableData" max-height="600" border fit>
      <el-table-column show-overflow-tooltip prop="id" label="ID" width="80">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="unit"
        label="单位名称"
        width=""
      >
      </el-table-column>

      <el-table-column label="操作" show-overflow-tooltip width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" @click="deleteBrand(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 60]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="outerVisible"
      :before-close="handleClosediaLoding"
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="formLabelAlign"
        :rules="rules"
        ref="ruleForm"
      >
        <div class="oneLine">
          <el-form-item label="单位名称" prop="name">
            <el-input v-model="formLabelAlign.name"></el-input>
          </el-form-item>
        </div>
        <!--  -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeVisible('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  uploadFilec,
  getGoodsUnit,
  setGoodsUnit,
  addGoodsUnit,
  delGoodsUnit,
  deleteSort,
} from "../../../../utils/api";
export default {
  name: "goodsUnit",
  data() {
    //这里存放数据
    return {
      token: sessionStorage.getItem("token"),
      topInputList: [{ title: "单位名称", text: "" }],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      total: 0,
      limit: 10,
      loading: true,
      outerVisible: false,
      formLabelAlign: {
        name: "",
        type: 1,
      },
      imgHeader: this.Global.imgHeader,

      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      bianjiFlag: false,
      rules: {
        name: [
          { required: true, message: "请输入单位名称", trigger: "change" },
        ],
      },
      dialogTitle: "",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let img = "";
          img = this.formLabelAlign.avatar ? this.formLabelAlign.avatar : "";
          let reg = /^[\u4e00-\u9fa5]{0,}$/g;
          if (!reg.test(this.formLabelAlign.name)) {
            this.$message({
              message: "请输入汉字",
              type: "error",
            });
            return;
          }
          if (this.bianjiFlag) {
            setGoodsUnit(
              this.token,
              this.formLabelAlign.name,
              0,
              1,
              this.formLabelAlign.id
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "保存成功",
                  type: "success",
                  onClose: (res) => {},
                });
                this.outerVisible = false;
                this.$refs.ruleForm.resetFields();

                this.formLabelAlign.atavar = "";
                this.formLabelAlign.avatar = "";
                this.formLabelAlign.id = "";
                this.formLabelAlign.name = "";
                this.formLabelAlign.sort = "";
                this.getGoodsUnit(this.token, this.currentPage, this.limit, 1);
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            addGoodsUnit(this.token, this.formLabelAlign.name, 0, 1).then(
              (res) => {
                if (res.data.status) {
                  this.$message({
                    message: "保存成功",
                    type: "success",
                  });
                  this.outerVisible = false;
                  this.$refs.ruleForm.resetFields();

                  this.getGoodsUnit(
                    this.token,
                    this.currentPage,
                    this.limit,
                    1
                  );
                  this.formLabelAlign.id = "";
                  this.formLabelAlign.name = "";
                } else {
                  this.$message.error(res.data.msg);
                }
              }
            );
          }
        } else {
          return false;
        }
      });
    },
    closeVisible(formName) {
      this.$refs[formName].resetFields();
      this.outerVisible = false;
      this.formLabelAlign.id = "";
      this.formLabelAlign.name = "";
    },
    handleClosediaLoding() {
      this.$refs.ruleForm.resetFields();
      this.outerVisible = false;
      this.formLabelAlign.id = "";
      this.formLabelAlign.name = "";
    },
    // 选中的用户

    handleSizeChange(val) {
      this.limit = val;
      // console.log(`每页 ${val} 条`);
      this.getGoodsUnit(this.token, this.currentPage, this.limit, 1);
    },
    // 第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getGoodsUnit(this.token, this.currentPage, this.limit, 1);
    },
    // 获取用户信息
    getGoodsUnit(token, page, limit, type) {
      this.loading = true;
      getGoodsUnit(token, page, limit, type).then((res) => {
        console.log(res.data);
        if (res.data.status) {
          this.tableData = res.data.data.data;
          this.total = res.data.data.count;
          this.tableData.forEach((item) => {
            item.aavatar = [];
            if (item.logo) {
              item.aavatar.push(this.imgHeader + item.logo);
            }
          });
          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
          this.loading = false;
          this.$message.error(res.data.msg);
          // let timer = setTimeout(()=>{
          //   this.$message.error('错误，请刷新');
          // },5000)
        }
      });
    },

    search() {
      this.getGoodsUnit(this.token, this.currentPage, this.limit, 1);
    },

    // 删除
    deleteBrand(index, row) {
      // console.log(row)
      this.$confirm("确定删除品牌吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delGoodsUnit(this.token, row.id, "").then((res) => {
            // console.log(res)
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getGoodsUnit(this.token, this.currentPage, this.limit, 1);
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleEdit(index, row) {
      this.bianjiFlag = false;
      this.outerVisible = true;
      this.dialogTitle = "创建";
      if (row) {
        this.bianjiFlag = true;
        this.dialogTitle = "编辑";
        this.formLabelAlign.name = row.unit;
        this.formLabelAlign.type = row.type;
        this.formLabelAlign.id = row.id;
        console.log(row);
      }
      console.log(this.formLabelAlign);
    },
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    handleRemove() {},
    //这是我自定义的移除事件
    handleClose(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //上传文件的事件
    uploadFile(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFilec(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          // console.log(res)
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.formLabelAlign.atavar = res.data.data.weburl;
          this.formLabelAlign.avatar = res.data.data.saveurl;
          this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
          let i = this.fileList.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClose();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // this.toAdd();

    this.getGoodsUnit(this.token, this.currentPage, this.limit, 1);
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
    <style scoped >
#app {
  width: 100%;
}

/deep/.header {
  background: white !important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
}

.top-input {
  width: 150px;
  margin-right: 20px;
}

/deep/.el-table th.el-table__cell > .cell {
  text-align: center;
}

/deep/.el-table--border .el-table__cell:first-child .cell {
  text-align: center;
}

/deep/.el-table .cell.el-tooltip {
  text-align: center;
}

.el-table {
  margin: 20px 0;
}

/deep/.el-checkbox:last-of-type {
  margin-left: 0;
}

.oneLine {
  display: flex;
  justify-content: space-between;
}

/deep/.el-dialog__wrapper .el-dialog {
  width: 35%;
}

/deep/.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}

.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
}
</style>
    